import axios from "axios";
import { message } from 'antd';
import FullLoading from "../views/components/FullLoading";

//-------------------------1. 创建axios实例-----------------------
const instance = axios.create({
    // 接口
    baseURL: "",
    // 超时时间
    timeout: 10000,
});
//-------------------------2.请求拦截-----------------------
instance.interceptors.request.use(
    config => {
        const token = sessionStorage.getItem('token');
        if (token) {
            config.headers['token'] = token
        }

        // 加载loading,默认有loading. // 用例 post('api/create', params, { isLoading: false });
        if (config.headers.isLoading !== false) {
            FullLoading.show();
        }

        return config;
    },
    error => {
        // 请求发生错误，抛出异常
        Promise.reject(error);
    }
);

//-------------------------3.响应拦截-----------------------
instance.interceptors.response.use(
    res => {

        // 取消加载 loading
        if (res.config.headers.isLoading !== false) {
            FullLoading.hide();
        }

        return res;
    },
    error => {

        // 取消加载 loading
        if (error.config.headers.isLoading !== false) {
            FullLoading.hide();
        }

        if (error && error.response) {
            const status = error.response.status
            switch (status) {
                case 400:
                    message.error("请求错误");
                    break;
                case 401:
                    message.error("未授权，请重新登录");
                    break;
                case 403:
                    message.error("登录过期，请重新登录");
                    break;
                case 404:
                    message.error("请求错误，未找到相应的资源");
                    break;
                case 408:
                    message.error("请求超时");
                    break;
                case 500:
                    message.error("服务器错误");
                    break;
                case 504:
                    message.error("网络超时");
                    break;
                default:
                    message.error("请求失败");
            }
        } else {
            if (JSON.stringify(error).includes("timeout")) {
                error.code = "TIMEOUT";
                error.message = "服务器响应超时，请刷新页面";
            }
        }
        return Promise.reject(error);
    },

);

// -------------------------配置全局loading-----------------------
// 4.导出 axios 实例
export default instance;